<template>
  <div class="page flex-c">
    <el-card style="width: 600px;">
      <div class="title">欢迎登录</div>
      <el-form ref="ruleFormRef" :model="formData" label-position="top" status-icon :rules="rules" class="demo-ruleForm">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" type="text" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="formData.pwd" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" style="width: 100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang='ts'>
  // 导入 store 仓库
  import { useStore } from '@/store/modules/user'
  // 导入路由实现编程式导航
  import { useRouter } from 'vue-router'
  import { reactive, ref } from 'vue'
  const store = useStore()
  const router = useRouter()
  const formData = reactive({
    userName: '',
    pwd: ''
  })
  const checkName = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('用户名不能为空'))
    } else {
      callback()
    }
  }
  const checkPwd = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('密码不能为空'))
    } else {
      callback()
    }
  }

  const rules = reactive({
    userName: [{ validator: checkName, trigger: 'blur' }],
    pwd: [{ validator: checkPwd, trigger: 'blur' }],
  })
  const ruleFormRef = ref(null)
  const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        store.login(formData)
        router.replace('/')
        ElMessage.success('登录成功！')
      } else {
        console.log('error submit!')
        return false
      }
    })
  }
</script>

<style scoped lang="scss">
  .page {
    width: 100%;
    height: 100%;
    background: linear-gradient(to right bottom, rgba(246, 248, 3, .3), rgba(17, 248, 214, .3), rgba(205, 17, 248, .3));

    .title {
      font-size: 34px;
      text-align: center;
      font-weight: 700;
      user-select: none;
      margin: 20px auto;
    }
  }
</style>